package com.haitaoit.chengquan.module.car.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.module.center.activity.xuqiu.PaySuccessActivity;
import com.haitaoit.chengquan.pay.alipay.Pay;
import com.haitaoit.chengquan.pay.alipay.Result;
import com.haitaoit.chengquan.pay.wxpay.Util;
import com.haitaoit.chengquan.pay.wxpay.WXPay;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class OrderPayActivity extends BaseActivity {
    @ViewInject(R.id.payment_cb1)
    CheckBox payment_cb1;
    @ViewInject(R.id.payment_cb2)
    CheckBox payment_cb2;
    @ViewInject(R.id.payment_cb3)
    CheckBox payment_cb3;
    @ViewInject(R.id.order_pay_money)
    TextView order_pay_money;


    private String order_no, order_amount;
    private String mFuwuseven;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_order_pay);
        ExitApplication.getInstance().addActivity(this);
        setTitle_V("订单支付");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        order_no = getIntent().getStringExtra("order_no");
        order_amount = getIntent().getStringExtra("order_amount");
        order_pay_money.setText("¥ " + order_amount);


        mFuwuseven = getIntent().getStringExtra("fuwuseven");
        httpGetcallback_url();
    }

    @OnClick({R.id.payway_ll1, R.id.payway_ll2, R.id.payway_ll3, R.id.go_payment})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.payway_ll1:
                payment_cb1.setChecked(true);
                payment_cb2.setChecked(false);
                payment_cb3.setChecked(false);
                break;
            case R.id.payway_ll2:
                payment_cb1.setChecked(false);
                payment_cb2.setChecked(true);
                payment_cb3.setChecked(false);
                break;
            case R.id.payway_ll3:
                payment_cb1.setChecked(false);
                payment_cb2.setChecked(false);
                payment_cb3.setChecked(true);
                break;
            case R.id.go_payment:
                if (payment_cb1.isChecked()) {
                    httpGetorder_pay_balance();
                } else if (payment_cb2.isChecked()) {// 支付宝
                    if (Constant.REC_URL_PAL != null && !Constant.REC_URL_PAL.equals("")) {
                        Pay.Pay_Pay(this, "成铨", order_no, Utils.format(Double.valueOf(order_amount)), mHandler1);
                    }
                } else if (payment_cb3.isChecked()) {// 微信
                    if (Constant.weixin_Notify_URl != null && !Constant.weixin_Notify_URl.equals("")) {
                        PreferenceUtils.setPrefString("pay_type", "car_order");
                        String new_order_no = order_no + "|" + Util.getTime();
                        WXPay wxPay = new WXPay(OrderPayActivity.this, new_order_no, "在线支付", Utils.format(Double.parseDouble(order_amount)));
                        wxPay.pay();
                    }
                }
                break;
        }
        super.onClick(v);
    }

    private void httpGetcallback_url() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, false, Constant.Getcallback_url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String ErrCode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(ErrCode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            Constant.REC_URL_PAL = js.getString("zfb_url");
                            Constant.weixin_Notify_URl = js.getString("wx_url");
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showToast("获取数据失败，请检查网路！");
            }
        });
    }

    // 余额
    private void httpGetorder_pay_balance() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getorder_pay_balance, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            Intent intent = new Intent(OrderPayActivity.this, PaySuccessActivity.class);

                           if (mFuwuseven==null) {
                               intent.putExtra("type", "car_order");
                           }else {
                               intent.putExtra("type", "fuwu");
                           }
                            startActivity(intent);
                            finish();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * 支付宝
     */
    final Handler mHandler1 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    Result resultObj = new Result((String) msg.obj);
                    String resultStatus = resultObj.resultStatus;
                    // 判断resultStatus
                    // 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 支付成功 跳到支付成功页面
                        Intent intent = new Intent(OrderPayActivity.this, PaySuccessActivity.class);
                        intent.putExtra("type", "car_order");
                        startActivity(intent);
                        finish();
                    } else {
                        // 判断resultStatus  为非“9000”则代表可能支付失败
                        // “8000”
                        // 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.showToast("支付结果确认中");
                        } else {
                            ToastUtils.showToast("支付失败");
                        }
                    }
                    break;
                }
                case 2: {
                    ToastUtils.showToast("检查结果为：" + msg.obj);
                    break;
                }
                default:
                    break;
            }
        }
    };

}
